package com.guoqi.marrydate.fm

import android.content.ComponentName
import android.content.Intent
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import com.guoqi.marrydate.DetailActivity
import com.guoqi.marrydate.MyAppWidgetProvider.Companion.CHANGE_DATA
import com.guoqi.marrydate.R
import com.guoqi.marrydate.flag.EventAdapter
import com.guoqi.marrydate.flag.FlagBean
import com.lxj.xpopup.XPopup
import kotlinx.android.synthetic.main.fm_flag.*
import org.litepal.LitePal
import org.litepal.crud.callback.FindMultiCallback


class FlagFm : Fragment() {

    companion object {

        var instance: FlagFm? = null

        fun newInstance(args: String): FlagFm {
            val fragment = FlagFm()
            val bundle = Bundle()
            bundle.putString("fragment", args)
            fragment.arguments = bundle
            return fragment
        }

    }


    private lateinit var eventList: ArrayList<FlagBean>
    private lateinit var eventAdapter: EventAdapter


    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(com.guoqi.marrydate.R.layout.fm_flag, container, false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        activity?.let {
            instance = this
            initUI()
            initData()
        }
    }

    private fun initUI() {
        fab.attachToListView(lv_event)
        eventList = ArrayList()
        eventAdapter = EventAdapter(activity!!, eventList)
        lv_event.adapter = eventAdapter
        lv_event.setOnItemClickListener { _, _, i, _ ->
            var intent = Intent(activity, DetailActivity::class.java)
            intent.putExtra("id", eventList[i].id)
            intent.putExtra("title", eventList[i].title)
            startActivityForResult(intent, 1000)
        }
        val builder = XPopup.Builder(context).watchView(lv_event)
        lv_event.setOnItemLongClickListener { adapterView, view, i, l ->
            val bean = eventList[i]
            var topStr = if (bean.sortNo == 99) {
                "取消置顶"
            } else {
                "置顶"
            }
            var importantStr = if (bean.sortNo == 50) {
                "取消重要"
            } else {
                "标为重要"
            }
            builder.asAttachList(arrayOf(topStr, importantStr, "复制", "删除"), intArrayOf(R.mipmap.ic_right_top, R.mipmap.ic_right_star, R.mipmap.ic_right_copy, R.mipmap.ic_right_del)
            ) { _, text ->

                when (text) {
                    "置顶" -> {
                        bean.sortNo = 99
                        bean.save()
                        initData()
                    }
                    "取消置顶" -> {
                        bean.sortNo = 0
                        bean.save()
                        initData()
                    }
                    "标为重要" -> {
                        bean.sortNo = 50
                        bean.save()
                        initData()
                    }
                    "取消重要" -> {
                        bean.sortNo = 0
                        bean.save()
                        initData()
                    }
                    "复制" -> {
                        var intent = Intent(activity, DetailActivity::class.java)
                        intent.putExtra("bean", bean)
                        startActivityForResult(intent, 1000)
                    }
                    "删除" -> {
                        XPopup.Builder(activity)
                                .asConfirm("提示", "确定要删除『 ${eventList[i].title} 』吗？") {
                                    LitePal.delete(FlagBean::class.java, bean.id)
                                    Toast.makeText(activity, "删除成功", Toast.LENGTH_SHORT).show()
                                    initData()
                                }.show()
                    }
                }
            }.show()
            true
        }

        fab.setColorNormalResId(com.guoqi.marrydate.R.color.colorAccent)
        fab.setColorPressedResId(com.guoqi.marrydate.R.color.pressed)
        fab.setShadow(true)
        fab.setOnClickListener {
            startActivityForResult(Intent(activity, DetailActivity::class.java), 1000)
        }
    }

    open fun initData() {
        LitePal.where("1=1").order("sortNo desc,case when date < (SELECT date('now')) then 0 else 1 end desc, date asc").findAsync(FlagBean::class.java).listen(object : FindMultiCallback {
            override fun <T> onFinish(t: List<T>) {
                eventList = t as ArrayList<FlagBean>
                if (eventList.isNotEmpty()) {
                    tv_none.visibility = View.GONE
                    lv_event.visibility = View.VISIBLE
                    eventAdapter.resetData(eventList)
                } else {
                    lv_event.visibility = View.GONE
                    tv_none.visibility = View.VISIBLE
                }
            }
        })
        var intent = Intent(CHANGE_DATA)
        intent.component = ComponentName(activity?.packageName, "com.guoqi.marrydate.MyAppWidgetProvider")
        activity?.sendBroadcast(intent)
    }

}